package com.datastructure.test.verifyipaddress;

public class VerifyIpAddress {

    public static void main(String[] args) {
        //String data = "e2e1";
        //System.out.println(data.charAt(1));
        VerifyIpAddress verifyIpAddress = new VerifyIpAddress();
        String Ip = "2001:0db8:85a3:0:0:8A2E:0370:7334:";
        String solve = verifyIpAddress.solve(Ip);
        System.out.println(solve);
    }

    public String solve (String IP) {
        // write code here
        if(isIPv4(IP)){
            return "IPv4";
        }
        if(isIPv6(IP)){
            return "IPv6";
        }
        return "Neither";
    }

    public boolean isIPv4(String IP){
        String[] split = IP.split("\\.");
        if(split.length!=4){
            return false;
        } else {
            for (String splitString : split) {
                int integer = 256;
                try {
                    integer = Integer.parseInt(splitString);
                } catch (Exception e){
                    return false;
                }
                if (integer < 1 || integer > 255) {
                    return false;
                }
                if (splitString.length() >= 2 && splitString.startsWith("0")) {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean isIPv6(String IP){
        if(IP.endsWith(":")){
            return false;
        }
        String[] split = IP.split(":");
        if(split.length!=8){
            return false;
        } else {
            for (String splitString : split) {
                if(splitString.equals("")){
                    return false;
                }
                String lowerCase = splitString.toLowerCase();
                for (int i = 0; i < lowerCase.length(); i++) {
                    if(lowerCase.charAt(i)>'f'){
                        return false;
                    }
                }
                if (splitString.startsWith("0")) {
                    if(splitString.length()>1){
                        if (splitString.charAt(1)=='0') {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}
